#include "table.h"

/**
 * 筛选算法
 * @param {table} *tab      顺序表
 * @param {int} k           位置
 * @param {int} m           顺序表长度
 */
void sift(table *tab, int k, int m) {
    int i, j , finished;
    i = k;
    j = 2 * i;
    tab -> r[0] = tab -> r[k];
    finished = 0;

    while (j <= m && !finished) {
        if (j < m && tab -> r[j + 1].key < tab -> r[j].key) {
            j++;
        }
        if (tab -> r[0].key <= tab -> r[j].key) {
            finished = 1;
        } else {
            tab -> r[i] = tab -> r[j];
            i = j;
            j = 2 * i;
        }
    }

    tab -> r[i] = tab -> r[0];
}

int main() {
    table tab;
    int i, n = 10;
    int arr[] = {0, 9, 8, 7, 6, 5, 4, 3, 2, 1};

    for(i = 0; i <= n; i++) {
        tab.r[i].key = arr[i];
    }

    sift(&tab, 1, n);

    for(i = 0; i <= n; i++) {
        printf("%d ", tab.r[i].key);
    }

    return 0;
}